package com.kaishengit.service;

import java.util.ArrayList;
import java.util.List;

import com.kaishengit.dao.GoalDao;
import com.kaishengit.dao.MessageDao;
import com.kaishengit.dao.TaskDao;
import com.kaishengit.entity.Goal;
import com.kaishengit.entity.GoalProgress;
import com.kaishengit.entity.Message;
import com.kaishengit.entity.Task;
import com.kaishengit.util.DateUtil;
import com.kaishengit.util.PKutil;
import com.kaishengit.util.SubS;

public class GoalService {
	private GoalDao dao=new GoalDao();
	private TaskDao tdao=new TaskDao();
	private MessageDao mdao=new MessageDao();
	
	public List<GoalProgress> findAllByprojectId(String id) {
		
		List<Goal> list=dao.findAllByprojectId(id);
		List<GoalProgress> gProgressList=new ArrayList<GoalProgress>();
		for(Goal goal:list){
			GoalProgress gp=new GoalProgress();
			gp.setGoal(goal);
			List<Task> tl=tdao.findByGoalId(goal.getId());
			int s=tl.size();
			int avgProgess=0;
			int total=0;
			for(Task task:tl){
				String prog=task.getProgress();
				total+=Integer.valueOf(prog);
				
			}
			if(s!=0){
				avgProgess=total/s;
			}else{
				avgProgess=0;
			}
			gp.setProgress(avgProgess);
			gProgressList.add(gp);
		}
		
		return gProgressList;
	}

	

	public void save(String name, String desc, String projectid,String userid) {
		Goal goal=new Goal();
		String id=PKutil.getPk();
		goal.setId(id);
		goal.setT_project_id(projectid);
		goal.setGdescription(desc);
		goal.setGname(name);
		dao.save(goal);
		
		/**
		 * 将新建目标的信息保存进message表中
		 * */
		Message mes=new Message();
		String mid=PKutil.getPk();
		String time=DateUtil.getNow();
		mes.setId(mid);
		mes.setDate(time);
		String descr=SubS.getSubString(desc);
		mes.setContent(descr);
		mes.setName(name);
		mes.setUserid(userid);
		mes.setProjectid(projectid);
		mes.setGoalid(id);
		mes.setType("goal");
		mdao.saveGoal(mes);
		
	}



	
	
	public Goal findByGoalId(String goalid) {
		
		return dao.findById(goalid);
	}


	public void update(String goalid, String name, String desc, String projectid) {
		dao.update(goalid,name,desc,projectid);
	}
	
	
	public GoalProgress findByGoalId(String goalid,String projectid){
		List<GoalProgress> gProgressList=findAllByprojectId(projectid);
		for(GoalProgress gp:gProgressList){
			String id=gp.getGoal().getId();
			if(id.equals(goalid)){
				return gp;
			}
		}
		return null;
	}



	public void del(String goalid) {
		dao.delByGoalId(goalid);
	}

}
